<?php

namespace IDock\Insurance\MACN;

use IDock\Common\BaseInterface\BuilderInterface;
use IDock\Common\Tools\XMLTools;
use IDock\Http\Request;
use IDock\Http\Response;
use IDock\Insurance\MACN\Response\AllMACNResponse;
use IDock\Insurance\MACN\Response\PolicyPaymentResponse;
use IDock\Insurance\MACN\Request\AllMACNRequest;

class Builder implements BuilderInterface
{
    protected $ip;

    protected $config;

    protected $userId;

    protected $passWord;

    protected $agrtNo;

    protected $interSalesmanCode;

    protected $companyCode;

    protected $operatorCode;

    protected $queryType;

    protected $queryDetail;

    protected $flag;


    public function getConfig(): array
    {
        return  $this->config;
    }

    public function execute(Request $request): Response
    {
        /*** @var AllMACNRequest $request */
        $request->loadConfig($this->config);

        $requestId = sha1(mt_rand(100000,999999));
        $this->inject($request,[
            'interSalesmanCode',
            'queryType',
            'queryDetail',
            'flag',
        ]);
        $request->setRequestId($requestId);

        $param = [
            'head' => [
                'requestType' => $request->getRequestType(),
                'messageId' => $requestId,
                'userId' => $this->config['userId'] ?? '',
                'passWord' => $this->config['passWord'],
                'ip' => $this->ip,
            ],
            'body' => $this->generate($request)
        ];


        $xml = XMLTools::ToXML($param,'packet','<?xml version="1.0" encoding="UTF-8"?>');
        /*        $xml = '<?xml version="1.0" encoding="UTF-8"?><packet><head><requestType>0012</requestType><userId>weixin</userId><messageId>8329ec1d-8d9b-4fa7-a661-72382944a4e3</messageId><passWord>123456</passWord><ip>10.192.21.88</ip></head><body><baseInfo/><policyInfo><orderId/><productCode>1359</productCode><agrtNo/><subAgrtNo/><interSalesmanCode/><companyCode>0216000005</companyCode><operatorCode>PS16401935</operatorCode><salesmanCode>PS16401935</salesmanCode><virtualOperatorCode>PS16401935</virtualOperatorCode><virtualSalesManCode/><lastEfcPolicyNo/><lastEfcExpiryDate/><previousPolicyNo_B/><lastBizExpiryDate/><operateDate>2020-09-11</operateDate><issueDate>2020-09-11</issueDate><argueSolution>1</argueSolution><arbitoryName/><agencyName/><certificateNo/><businessNature>00101</businessNature><contractNo/><partnerId/><partnerName/><renewInd/><renewalNo/><publicStoreCode>wx02160640005</publicStoreCode></policyInfo><holderInfo><personType/><personName/><identifyType/><identifyNumber/><address/><mobilePhone/><contactName/><email/><telephone/></holderInfo><insuredInfo><personType/><personName/><identifyType/><identifyNumber/><address/><mobilePhone/><contactName/><email/><telephone/></insuredInfo><itemInfo><insuredNature>1</insuredNature><insuredType>3</insuredType><unitType/><identifyType>01</identifyType><ownerIdentifyNumber>410611199510248524</ownerIdentifyNumber><idcardstartdate>2019-10-07</idcardstartdate><idcardenddate>2023-06-07</idcardenddate><countryNature/><useYears/><completeKerbMass>1160.0</completeKerbMass><damagedFactorGrade/><carOwner>尤雪艳</carOwner><plateNum>暂未上牌</plateNum><isFieldCar>0</isFieldCar><plateColor>01</plateColor><plateType>02</plateType><frameNo>LZWACAGA7G6699488</frameNo><engineNum>JG42829984</engineNum><singeinDate>2016-09-02</singeinDate><isNew>0</isNew><enrollDate>2016-09-02</enrollDate><brandName>五菱LZW6407BCY多用途乘用车</brandName><printBrandName>五菱LZW6407BCY多用途乘用车</printBrandName><modelCode>WLD1950TYW</modelCode><colorCode/><carModelName>五菱LZW6407BCY多用途乘用车</carModelName><runMiles>0.0</runMiles><motorType>100</motorType><carKindCodeShow>A0</carKindCodeShow><seatCount>7</seatCount><tonCount>0.000</tonCount><exhaustScale>1206.0</exhaustScale><power>0.0</power><wholeWeight>1160.0</wholeWeight><attachNature>01</attachNature><carUseType>01</carUseType><useNatureShow>02</useNatureShow><purchasePrice>36000.00</purchasePrice><actualValue>25632.00</actualValue><runAreaCode/><carTypeCode/><carType1>A</carType1><carType2>02</carType2><carType3>068</carType3><jgVehicleType>K33</jgVehicleType><groupCode>0</groupCode><vehicleClass/><isTransfer>0</isTransfer><isTransferDate/><noDamageYears/><loanVehicleFlag>0</loanVehicleFlag><firstBeneficiary/><firstBeneficiaryName/><certificateDate>2016-09-02</certificateDate><settleAddressCode/><specialCarFlag/><carCheckStatus/><carChecker/><carCheckTime/><carCheckReason/></itemInfo><forceRiskInfo><riskCode>0806</riskCode><startDate>2023-10-18</startDate><endDate>2021-10-18</endDate><startTime>0:0</startTime><endTime>24:0</endTime><effectFlag>1</effectFlag><itemKindInfo><itemKindNo>1</itemKindNo><kindCode>BZ</kindCode><sumInsured>200000</sumInsured><rate/><unitInsured/><quantity/><discount/><premium/><discountPremium/></itemKindInfo><carShipTaxInfo><startTaxDate>2023-01-01</startTaxDate><taxCertificateno1/><revenue/><insuredName/><taxPayerName/><taxpayerCertiType>01</taxpayerCertiType><identifyNumber/><taxPayerPhoneNumber/><taxPayerNo/><declareDate/><departmentNolocal/><taxRegistryNumber>410611199510248524</taxRegistryNumber><TAXPAYERADDRESS/><lastTaxDate>2019-01-01</lastTaxDate><taxStartDate>2020-01-01</taxStartDate><taxEndDate>2020-12-31</taxEndDate><taxCompancyCode/><taxCompancyName/><taxDocumentNumber/><deductionDueCode/><taxDepartmentDode/><deDuctiondueType/><deDuctiondueProportion/><deDuction/><deDuctionDocumentNumber/><taxFlag>N</taxFlag><taxPayerCertiCode>01</taxPayerCertiCode><taxPayerIdentificationCode/><taxDepartmentCode/><taxDepartment/><noTaxCarType/><taxDocumentDate/></carShipTaxInfo></forceRiskInfo><businessRiskInfo><riskCode>0812</riskCode><startDate>2023-10-18</startDate><endDate>2023-10-18</endDate><startTime>0:0</startTime><endTime>24:0</endTime><effectFlag>1</effectFlag><bizCharge/><bizDiscount/><itemKindList><itemKindInfo><kindInd>1</kindInd><itemKindNo>2</itemKindNo><kindName>车损险</kindName><kindCode>A</kindCode><sumInsured>25632.00</sumInsured><rate/><deductibleRate/><deductible>0.0</deductible><modeCode/><unitInsured>0</unitInsured><quantity>0</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>1</kindInd><itemKindNo>10</itemKindNo><kindName>第三者责任保险</kindName><kindCode>B</kindCode><sumInsured>500000.00</sumInsured><rate/><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>0</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>1</kindInd><itemKindNo>16</itemKindNo><kindName>车上人员责任保险（司机）</kindName><kindCode>D11</kindCode><sumInsured>10000</sumInsured><rate/><deductibleRate/><deductible/><modeCode/><unitInsured>10000</unitInsured><quantity>1</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>1</kindInd><itemKindNo>20</itemKindNo><kindName>车上人员责任险（乘6)</kindName><kindCode>D12</kindCode><sumInsured>60000</sumInsured><rate/><deductibleRate/><deductible/><modeCode/><unitInsured>10000</unitInsured><quantity>6</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>1</kindInd><itemKindNo>24</itemKindNo><kindName>道路救援服务特约条款</kindName><kindCode>DLJY</kindCode><sumInsured>0</sumInsured><rate/><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>5</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>1</kindInd><itemKindNo>25</itemKindNo><kindName>车辆安全检测特约条款</kindName><kindCode>CLAQ</kindCode><sumInsured>0</sumInsured><rate/><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>1</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>1</kindInd><itemKindNo>26</itemKindNo><kindName>代为驾驶服务特约条款</kindName><kindCode>DWJS</kindCode><sumInsured>0</sumInsured><rate/><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>1</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>1</kindInd><itemKindNo>27</itemKindNo><kindName>代为送检服务特约条款</kindName><kindCode>DWSJ</kindCode><sumInsured>0</sumInsured><rate/><deductibleRate/><deductible/><modeCode>NVI</modeCode><unitInsured>0</unitInsured><quantity>1</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>2</kindInd><itemKindNo>3</itemKindNo><kindName>附加车轮单独损失险</kindName><kindCode>CL</kindCode><sumInsured>2000.00</sumInsured><rate>0</rate><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>0</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>2</kindInd><itemKindNo>5</itemKindNo><kindName>附加车身划痕损失险</kindName><kindCode>L</kindCode><sumInsured>2000</sumInsured><rate/><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>0</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>2</kindInd><itemKindNo>7</itemKindNo><kindName>附加修理期间费用补偿险</kindName><kindCode>C</kindCode><sumInsured>300.00</sumInsured><rate/><deductibleRate/><deductible/><modeCode/><unitInsured>300.0</unitInsured><quantity>1</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>2</kindInd><itemKindNo>8</itemKindNo><kindName>附加发动机损坏除外特约条款</kindName><kindCode>FDJ</kindCode><sumInsured>0.0</sumInsured><rate/><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>0</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>2</kindInd><itemKindNo>9</itemKindNo><kindName>附加绝对免赔率特约条款（车损险）</kindName><kindCode>AA</kindCode><sumInsured>0</sumInsured><rate>5</rate><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>0</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>2</kindInd><itemKindNo>12</itemKindNo><kindName>附加法定节假日限额翻倍险</kindName><kindCode>B2</kindCode><sumInsured>500000</sumInsured><rate/><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>0</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>2</kindInd><itemKindNo>14</itemKindNo><kindName>附加绝对免赔率特约条款（第三者责任保险）</kindName><kindCode>AB</kindCode><sumInsured>0</sumInsured><rate>5</rate><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>0</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>2</kindInd><itemKindNo>13</itemKindNo><kindName>附加精神损害抚慰金责任险（第三者责任保险）</kindName><kindCode>B3</kindCode><sumInsured>5000</sumInsured><rate/><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>0</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>2</kindInd><itemKindNo>15</itemKindNo><kindName>附加医保外用药责任险（第三者责任保险）</kindName><kindCode>B4</kindCode><sumInsured>0</sumInsured><rate/><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>0</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>2</kindInd><itemKindNo>17</itemKindNo><kindName>附加绝对免赔率特约条款（车上人员责任保险（司机））</kindName><kindCode>AD11</kindCode><sumInsured>0</sumInsured><rate>5</rate><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>0</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>2</kindInd><itemKindNo>18</itemKindNo><kindName>附加精神损害抚慰金责任险（车上人员责任保险（司机））</kindName><kindCode>D13</kindCode><sumInsured>5000</sumInsured><rate/><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>0</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>2</kindInd><itemKindNo>19</itemKindNo><kindName>附加医保外用药责任险（车上人员责任保险（司机））</kindName><kindCode>D14</kindCode><sumInsured>0</sumInsured><rate/><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>0</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>2</kindInd><itemKindNo>21</itemKindNo><kindName>附加绝对免赔率特约条款（车上人员责任保险（乘客））</kindName><kindCode>AD12</kindCode><sumInsured>0</sumInsured><rate>5</rate><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>0</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>2</kindInd><itemKindNo>22</itemKindNo><kindName>附加精神损害抚慰金责任险（车上人员责任保险（乘客））</kindName><kindCode>D22</kindCode><sumInsured>5000</sumInsured><rate/><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>0</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo><itemKindInfo><kindInd>2</kindInd><itemKindNo>23</itemKindNo><kindName>附加医保外用药责任险（车上人员责任保险（乘客））</kindName><kindCode>D23</kindCode><sumInsured>0</sumInsured><rate/><deductibleRate/><deductible/><modeCode/><unitInsured>0</unitInsured><quantity>0</quantity><discount/><premium/><discountPremium/><relatedInd>0</relatedInd></itemKindInfo></itemKindList></businessRiskInfo><expectDiscount/></body></packet>';*/
        $xml = str_replace('proposalNo1','proposalNo',$xml);
        $request->setPreParameter($xml);
        $request->setBizParam($xml);
        return $this->request($request);
    }

    private function inject($request,$arr)
    {
        foreach ($arr as $property){
            if(property_exists($request,$property)){
                $request->$property = $this->$property;
            }
        }

    }

    /**
     * 支付接口
     * @param Request $request
     * @return Response
     */
    public function payment(Request $request)
    {
        $request->loadConfig($this->config);

        $requestId = sha1(uniqid('', true));

        $request->setRequestId($requestId);

        $param = $request->generate();

        $request->setBizParam($param);
        $payUrl =  $request->getPayUrl();

        $response = new PolicyPaymentResponse(200);

        $response->setUrl($payUrl);

        return  $response;
    }

    public function generate(Request $request): array
    {
        return $request->generate();
    }

    public function sign(Request $request): Request
    {
        return $request;
    }

    public function exceptionResponse($request, $errorMessage): Response
    {
        $response = $request->getResponse();

        $response = new $response;
        $response->setCode('500');
        $response->setError($errorMessage);

        return $response;
    }

    public function request(Request $request): Response
    {
        $response = $request->request($request);
        $response->setVisitor($request->getVisitor());

        if(!$response->isSuccess()){
            return $response;
        }
        $response->printerInit();
        return $response;
    }

    public function encrypt(Request $request)
    {
    }
}


